<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\View;
use App\Core\CSRF;
use App\Core\RateLimit;
use App\Core\Session;
use App\Core\Flash;
use App\Services\Auth;

final class AuthController
{
    public function showLogin(): string
    {
        // 记录用户原本想访问的页面
        if (!isset($_SESSION['intended_url']) && isset($_SERVER['HTTP_REFERER'])) {
            $referer = $_SERVER['HTTP_REFERER'];
            $currentHost = $_SERVER['HTTP_HOST'] ?? '';

            // 只记录同域名的页面，避免开放重定向漏洞
            if (strpos($referer, $currentHost) !== false) {
                $path = parse_url($referer, PHP_URL_PATH);
                if ($path && $path !== '/login' && $path !== '/register') {
                    $_SESSION['intended_url'] = $path;
                }
            }
        }

        return View::render('auth/login', [
            'title' => '登录',
        ]);
    }

    public function login(): string
    {
        CSRF::validateOrAbort();

        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $rateLimitKey = 'login_' . $ip;

        // 检查是否被限速
        if (!RateLimit::check($rateLimitKey)) {
            $remainingTime = RateLimit::getRemainingTime($rateLimitKey);
            $minutes = ceil($remainingTime / 60);
            http_response_code(429);
            return "登录失败次数过多，请 {$minutes} 分钟后再试";
        }

        $identity = trim((string)($_POST['identity'] ?? ''));
        $password = (string)($_POST['password'] ?? '');

        if ($identity === '' || $password === '') {
            http_response_code(400);
            return '请输入账号与密码';
        }

        if (!Auth::attempt($identity, $password)) {
            // 记录失败尝试
            RateLimit::record($rateLimitKey);
            Flash::error('用户名/邮箱或密码错误');
            header('Location: /login');
            exit;
        }

        Flash::success('登录成功，欢迎回来！');

        // 重定向到用户原本想访问的页面，或默认首页
        $redirectUrl = $_SESSION['intended_url'] ?? '/';
        unset($_SESSION['intended_url']); // 清除记录的URL

        header('Location: ' . $redirectUrl);
        exit;
    }

    public function logout(): string
    {
        Auth::logout();
        Flash::info('您已安全退出');
        header('Location: /');
        exit;
    }

    public function showRegister(): string
    {
        return View::render('auth/register', [
            'title' => '注册',
        ]);
    }

    public function register(): string
    {
        CSRF::validateOrAbort();
        $username = trim((string)($_POST['username'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $password2 = (string)($_POST['password2'] ?? '');

        if ($username === '' || $email === '' || $password === '') {
            http_response_code(400);
            return '请填写完整信息';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            return '邮箱格式不正确';
        }
        if ($password !== $password2) {
            http_response_code(400);
            return '两次输入的密码不一致';
        }

        try {
            Auth::register($username, $email, $password);
            Flash::success('注册成功，欢迎加入！');
        } catch (\Throwable $e) {
            Flash::error('注册失败：' . $e->getMessage());
            header('Location: /register');
            exit;
        }

        header('Location: /');
        exit;
    }
}
